package com.lalilu.lread.utils

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream

@Throws(Exception::class)
suspend fun ByteArray.compressBytesToFormat(
    quality: Int,
    format: Bitmap.CompressFormat
): ByteArray = withContext(Dispatchers.IO) {
    val byteArray = this@compressBytesToFormat

    val bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
    val output = ByteArrayOutputStream()
    bitmap.compress(format, quality, output)
    bitmap.recycle()
    return@withContext output.toByteArray()
}

@Throws(Exception::class)
suspend fun ByteArray.saveToPath(
    path: String,
): Uri? = withContext(Dispatchers.IO) {
    return@withContext FileUtil.saveFile(path, this@saveToPath)
}

object BitmapUtil {

    suspend fun compressBytesToFormat(
        bytes: ByteArray?,
        quality: Int,
        format: Bitmap.CompressFormat
    ): ByteArray? = withContext(Dispatchers.IO) {
        if (bytes == null || bytes.isEmpty()) return@withContext bytes

        try {
            val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
            val output = ByteArrayOutputStream()
            bitmap.compress(format, quality, output)
            bitmap.recycle()
            return@withContext output.toByteArray()
        } catch (e: Exception) {
            println("Exception: " + e.message)
        }
        return@withContext bytes
    }

    suspend fun saveAsWebp(
        path: String,
        bytes: ByteArray,
        quality: Int,
    ): Uri? = withContext(Dispatchers.IO) {
        if (bytes.isEmpty()) return@withContext null

        try {
            val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
            val output = ByteArrayOutputStream()
            bitmap.compress(Bitmap.CompressFormat.WEBP_LOSSY, quality, output)
            bitmap.recycle()
            return@withContext FileUtil.saveFile(path, output.toByteArray())
        } catch (e: Exception) {
            println("Exception: " + e.message)
        }
        return@withContext null
    }


}